<template>
  <el-dialog
    top="30px"
    width="1000px"
    title="资料要件"
    append-to-body
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="beforeClose"
  >
    <attach-detail :project-data="projectData"></attach-detail>
    <attach-upload
      :tags="uploadTags"
      :batch-no="relatedId"
      :view-mode="isView"
      v-bind="$listeners"
      @after-data="handleAfterData"
    >
      <template slot="header">
        <h3 class="attach-title">附件资料</h3>
        <hr />
      </template>
      <template slot="contract">
        <attach-contract
          :related-id="relatedId"
          :tag="contractTag"
          :view-mode="isView"
          @get-contract="handleGetContract"
          @after-data="handleAfterData"
          @type-change="handleContractTypeChange"
          @success="handleContractSuccess"
        ></attach-contract>
      </template>
      <template slot="application">
        <attach-application
          :project-data="projectData"
          :sign-data="signData"
          :tag="applicationTag"
          :view-mode="isView"
          @after-data="handleAfterData"
          @type-change="handleApplicationTypeChange"
          @success="handleContractSuccess"
        ></attach-application>
      </template>
    </attach-upload>
  </el-dialog>
</template>

<script>
import { projectIsCompany } from '@/bank/views/fast/index'
import { enumPersonalTags, enumCompanyTags } from '@/bank/views/fast/attach'

import AttachDetail from '@/bank/views/fast/AttachDetail'
import AttachUpload from '@/bank/components/attach/Upload'
import AttachContract from '@/bank/views/fast/AttachContract'
import AttachApplication from '@/bank/views/fast/AttachApplication'
const contractSlot = 'contract'
const applicationSlot = 'application'

export default {
  components: {
    AttachDetail,
    AttachUpload,
    AttachContract,
    AttachApplication,
  },
  props: {
    visible: Boolean,
    viewMode: Boolean,
    projectData: {
      type: Object,
      default: () => ({}),
    },
    updateAttachStatus: Boolean,
  },
  data() {
    return {
      isOnlineSign: 2,
      attachs: [],
      signStatus: 0,
      customerSignApproval: 0,
      signData: {},
      applicationIsOnline: 0,
    }
  },
  computed: {
    isCompany() {
      return projectIsCompany(this.projectData)
    },
    uploadTags() {
      return this.isCompany ? enumCompanyTags : enumPersonalTags
    },
    relatedId() {
      return this.projectData.customer_related_id
    },
    contractTag() {
      const tag = this.uploadTags.find(it => it.slot === contractSlot) || {}
      return {
        parentTag: tag.parentTag,
        tag: tag.tag,
        required: tag.required,
      }
    },
    applicationTag() {
      const tag = this.uploadTags.find(it => it.slot === applicationSlot) || {}
      return {
        parentTag: tag.parentTag,
        tag: tag.tag,
        required: tag.required,
      }
    },
    isView() {
      return +this.projectData.recommend_status > 0 || this.viewMode
    },
  },
  watch: {
    projectData: {
      handler: function () {
        this.applicationIsOnline = this.projectData.is_online_sign
        this.getSignData()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleApplicationTypeChange(type) {
      this.applicationIsOnline = type
      this.getSignData().then(() => {
        this.updateStatus()
      })
    },
    getSignData() {
      return this.$api
        .getData({
          table: 'customer_apply_sign',
          params: {
            'sign_type.eq': 1,
            'customer_related_id.eq': this.relatedId,
          },
          order: { create_time: 'desc' },
        })
        .then(res => {
          this.signData = res?.data?.[0] ?? {}
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
    handleAfterData({ list, emit }) {
      if (!this.updateAttachStatus) return
      this.attachs = list
      if (emit) {
        this.updateStatus()
      }
    },

    // 委托合同附件
    handleGetContract({ contract }) {
      this.isOnlineSign = +(contract.is_online_sign || 0)
      this.signStatus = +(contract.sign_status || 0)
      this.customerSignApproval = +(contract.customer_sign_approval || 0)
    },
    handleContractTypeChange(type) {
      this.isOnlineSign = type
      this.updateStatus()
    },
    handleContractSuccess() {
      this.signStatus = 1
      this.updateStatus()
    },

    // 更新项目附件状态
    updateStatus() {
      // 判断附件状态
      const listObj = this.attachs.reduce((prev, curr) => {
        const tag = curr.attachment_type
        if (!prev[tag]) prev[tag] = []
        prev[tag].push(curr)
        return prev
      }, {})
      const isAllUpload = this.uploadTags.every(tag => {
        const isOnline = tag.slot === contractSlot && this.isOnlineSign === 1
        const applicationIsonline = tag.slot === applicationSlot && +this.applicationIsOnline === 1
        if (applicationIsonline) {
          return +this.signData.sign_status === 2
        }
        if (isOnline) {
          return this.customerSignApproval === 1
        }
        if (!tag.required) return true
        const atts = listObj[tag.tag]
        return atts && atts.length > 0
      })
      const currentStatus = isAllUpload ? 1 : 0
      const attachStatus = +this.projectData.datum_status
      if (attachStatus === currentStatus) return this.$emit('after-data', {})

      // 更新状态
      this.$api
        .updateData({
          table: 'customer_related_quick',
          id: this.relatedId,
          data: {
            datum_status: currentStatus,
          },
        })
        .then(() => {
          // 观察：更改 props 对象值
          this.projectData.datum_status = currentStatus
          this.$emit('after-data', true)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.attach-title {
  font-size: 1.1rem;
  font-weight: bold;
}
</style>
